<?php
/**
 * Klasse zum sammeln und analysieren von Benutzer angeklickte regionen
 * zur Erfolgskontrolle
 *
 * @author		Joachim Ruf
 * @copyright	Copyright (c) 2003-2010 Loresoft Software (http://www.loresoft.de)
 * @license		http://yapary.loresoft.de/lizenzbedingungen     New BSD License
 *
 * */


Class Yapary_Marketing_Heatmap
{
    const NEWLINE = '&#13;';

    private $oSql            = NULL;
    private $oHeader         = NULL;
    private $siteName        = NULL;
    private $urlWebinterface = NULL;
    private $dbTableName     = 'yapary_heatmap';

    /** @var Links-/Rechtsverschiebung des gesamten Konstrukts */
    private $moveX    = -5;
    private $moveY    = -5;


    function __construct (Yapary_Db_Sql_Connector $_oSql, Yapary_Header_Header $_cHeader, $_urlWebinterface, $_siteName)
    {
		if (!$_oSql->isTableExists($this->dbTableName)) {
            $e = new Exception();
            $arrTrace = $e->getTrace();
            $trace = '<b>'.$arrTrace[0]['class'].$arrTrace[0]['type'].$arrTrace[0]['function'].'</b> in <b>'.$arrTrace[0]['file'].'</b> on line <b>'.$arrTrace[0]['line'].'</b>';
            trigger_error('<pre></b>No database installed<br />'.$trace.'</pre>', E_USER_WARNING);
		}

		$this->urlWebinterface = $_urlWebinterface;
		$this->oSql            = $_oSql;
		$this->oHeader         = $_cHeader;
		$this->setSiteName($_siteName);
    }


    /**
     * Definiert den mit den Daten zu verknuepfenden eindeutigen Namen
     * @param string $_siteName	: Seitenname
     * @return bool
     * */
    public function setSiteName ($_siteName)
    {
		$this->siteName = $_siteName;
		$result = $this->oHeader->addJsCode('Heatmap',
                                            'Heatmap = new Heatmap("'.$_siteName.'", "'.$this->urlWebinterface.'");'
                                    	   .'Heatmap.register();');
        // Falls Heatmap JS-Code existiert, loesche diesen und setze ihn neu
        if ($result == false) {
            $this->oHeader->deleteJsCode('Heatmap');
            return $this->setSiteName($_siteName);
        }

        return true;
    }


    /**
     * Nimmt eine Links-/Rechtsverschiebung des gesamten Konstruktes vor um eine
     * Zentrierung vornehmen zu koennen, falls die Anzeige nicht am oberen linken
     * Punkt eingefuegt werden kann
     * @param int $left	: Verschiebung auf der X-Achse
     * @param int $top	: Verschiebung auf der Y-Achse
     * @return bool
     * */
    public function moveXY ($left, $top)
    {
        if (!is_numeric($left) || !is_numeric($top)) {
            return false;
        }

        $this->moveX = $left;
        $this->moveY = $top;
        return true;
    }


    /**
     * Fuegt einen neuen Datensatz hinzu
     * @param int $x			: X-Position des Mausklicks
     * @param int $y			: Y-Position des Mausklicks
     * @param string $tagName	: Name des Tags
     * @return bool
     * */
    public function add ($x, $y, $tagName)
    {
        $result = NULL;

        if (!is_numeric($x) || !is_numeric($y)) {
            return false;
        }
        if (strlen($tagName) > 255) {
            return false;
        }

        $ip    = $_SERVER["REMOTE_ADDR"];
        $dns   = htmlentities(strip_tags(gethostbyaddr(getenv("REMOTE_ADDR"))));
        $agent = htmlentities(strip_tags(getenv("HTTP_USER_AGENT")));

        $oDbResult = $this->oSql->request("INSERT INTO heatmap
    								(X, Y, Tag, Ip, Dns, Agent, SiteName)
    								VALUES (:x, :y, :tag, :ip, :dns, :agent, :siteName)",
                                    array('x'       => $x,
                                          'y'       => $y,
                                          'tag'     => $tagName,
                                          'ip'      => $ip,
                                          'dns'     => $dns,
                                          'agent'   => $agent,
                                          'siteName' => $this->siteName));
        return true;
    }


    public function delete ($id)
    {
        if ($this->siteName == NULL) {
            trigger_error('no SiteName defined!', E_USER_NOTICE);
        }

        $this->oSql->request("DELETE FROM heatmap WHERE Id=:id",
                                    array('id' => $id));
        return true;
    }


    /**
     * Loescht alle Informationen
     * @return bool
     * */
    public function clear ($_dateFrom, $_dateTo = NULL)
    {
        if ($_dateTo == NULL) {
            $_dateTo = $_dateFrom;
        }

        $oDbResult = $this->oSql->request("DELETE FROM heatmap WHERE DATE(DateTime)>=:dateFrom AND DATE(DateTime)<=:dateTo",
                                    array('dateFrom' => $_dateFrom,
                                          'dateTo'   => $_dateTo));
        return true;
    }


    /**
     * Liefert die Daten als Array
     * @return array : array[$id] = array('x'=>$x, 'y'=>$y, 'tag'=>$tag, 'ip'=>$ip, 'dns'=>$dns, 'agent'>=$agent, 'dateTime'=>$dateTime)
     * */
    public function getList ($_dateFrom, $_dateTo = NULL)
    {
        $arrResult = array();

        if ($_dateTo == NULL) {
            $_dateTo = $_dateFrom;
        }

        $oDbResult = $this->oSql->request("SELECT *
        					  FROM heatmap
        					  WHERE DATE(DateTime)>=:dateFrom AND DATE(DateTime)<=:dateTo",
                              array('dateFrom' => $_dateFrom,
                                    'dateTo'   => $_dateTo));

        if ($oDbResult->getCount() == 0) {
            return $arrResult;
        }

        while ($row = $oDbResult->getNext()) {
            $arrResult[$row->Id] = array('x' => $row->X,
                                         'y' => $row->Y,
                                         'tag' => $row->Tag,
                                         'ip' => $row->Ip,
                                         'dns' => $row->Dns,
                                         'agent' => $row->Agent,
                                         'dateTime' => $row->DateTime);
        }

        return $arrResult;
    }


    /**
     * Zeigt die angeklickten Areale fuer das ausgewaehlte Datum an
     * @param string $_dateFrom				: Anfangsdatum im Format YYYY-MM-DD
     * @param string $_dateFrom [optional]	: Enddatum im Format YYYY-MM-DD
     * @return string
     * */
    public function display ($_dateFrom, $_dateTo = NULL)
    {
        $result = '';

        if ($_dateTo == NULL) {
            $_dateTo = $_dateFrom;
        }

        $oDbResult = $this->oSql->request("SELECT *
        					  FROM heatmap
        					  WHERE SiteName='$this->siteName' AND DATE(DateTime)>=:dateFrom AND DATE(DateTime)<=:dateTo
        					  ORDER BY DateTime",
                              array('dateFrom' => $_dateFrom,
                                    'dateTo'   => $_dateTo));


        if ($oDbResult->getCount() == 0) {
            return '';
        }


        while ($row = $oDbResult->getNext()) {
            $title = 'Ip: '.$row->Ip.self::NEWLINE
                   . 'TagName: '.$row->Tag.self::NEWLINE
                   . 'DateTime: '.$row->DateTime;
            $result .= '<div class="heatmapPixel" style="left: '.$row->X.'px; top: '.$row->Y.'px;" title="'.$title.';"></div>';
        }

        return '<div class="heatmap">
        			<div class="heatmapContent" style="top: '.$this->moveY.'px; left: '.$this->moveX.'px;">
        				'.$result.'
        			</div>
        		</div>';
    }


    /**
     * Gibt eine Mindmap mit den auf der vorgegebenen Seite angeklickten Bereiche an
     * @param string $_dateFrom				: Anfangsdatum im Format YYYY-MM-DD
     * @param string $_dateFrom [optional]	: Enddatum im Format YYYY-MM-DD
     * @return gdimage
     * */
    public function displayMindmap ($_dateFrom, $_dateTo = NULL)
    {
        $result = '';

        if ($_dateTo == NULL) {
            $_dateTo = $_dateFrom;
        }

        $oDbResult = $this->oSql->request("SELECT DISTINCT Tag
        					  FROM heatmap
        					  WHERE SiteName='$this->siteName' AND DATE(DateTime)>=:dateFrom AND DATE(DateTime)<=:dateTo",
                              array('dateFrom' => $_dateFrom,
                                    'dateTo'   => $_dateTo));


        if ($oDbResult->getNext() == 0) {
            return '';
        }


        $width  = 300;
        $height = 300;
        $pointSize = 30;
        $gdImage = imagecreate($width, $height);
        imagefilledellipse($gdImage, $width-$pointSize/2, $height-$pointSize/2, $pointSize, $pointSize, imagecolorallocate($gdImage, 255, 0, 0));
        while ($row = $this->oSql->nextData()) {
        }

        header('Content-type: image/png');
        return imagepng($gdImage);
    }

}


?>